
//
//  NearbyViewController.m
//  Lovely Food
//
//  Created by 李经纬 on 15/11/27.
//  Copyright © 2015年 李经纬. All rights reserved.
//

#import "NearbyViewController.h"
#import <BaiduMapAPI_Base/BMKBaseComponent.h>//引入base相关的所有头文件
#import <BaiduMapAPI_Map/BMKMapComponent.h>//引入地图功能的所有的头文件
#import <BaiduMapAPI_Search/BMKSearchComponent.h>//引用搜索功能的都所有的头文件
#import <BaiduMapAPI_Location/BMKLocationComponent.h>//引用定位功能的所有的头文件
#import <BaiduMapAPI_Utils/BMKUtilsComponent.h>//引用计算功能的所得头文件
#import <BaiduMapAPI_Radar/BMKRadarComponent.h>//计算所有雷达功能的头文件
#import <BaiduMapAPI_Map/BMKMapView.h>//只引用所需的单个头文件




@interface NearbyViewController ()<BMKMapViewDelegate,BMKGeneralDelegate,BMKLocationServiceDelegate,BMKPoiSearchDelegate,BMKGeoCodeSearchDelegate,UITextFieldDelegate>

@property (nonatomic,strong)BMKMapManager *mapManager;
//地图
@property (nonatomic,strong)BMKMapView *mapView;
//定位button
@property (nonatomic,strong)UIButton *bt_locaition;
//定位服务
@property (nonatomic,strong)BMKLocationService *localService;
//当前经纬度
@property (nonatomic,assign)float current_location;
@property (nonatomic,assign)float current_latitude;

//搜索
@property (nonatomic,strong)UITextField *textField;
@property (nonatomic,strong)UIButton *bt_cancel;
//寻找
@property (nonatomic,strong)BMKPoiSearch *searcher;
@property (nonatomic,assign)int curPage;
//检索
@property (nonatomic,strong)BMKPoiSearch *poiSearch;

//地理编码
@property (nonatomic,strong)BMKGeoCodeSearch *geoCodeSearch;
//切换卫星/普通模式
@property (nonatomic,strong)BMKGeoCodeSearch *geocodesearch;
@property (nonatomic,strong)UIButton *btn_big;
@property (nonatomic,strong)UIButton *btn_small;

//路况
@property (nonatomic,strong)UIButton *bt_road;


@end

@implementation NearbyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor yellowColor];
    
    //    //创建百度地图引擎对象（使用百度地图功能之前必须启动引擎）
    //    self.mapManager = [[BMKMapManager alloc] init];
    //    //如果要关注网络及授权验证事件，请设定generalDelegate参数
    //    BOOL ret = [self.mapManager start:@"dI1Rt0OoN40lnRDsCny7PxBN" generalDelegate:self];
    //    if (!ret) {
    //        NSLog(@"manager start failed !");
    //    }else{
    //        NSLog(@"打开地图成功");
    //    }
    
    //self.navigationItem.title = @"定位";
    [self p_addMapView];
    [self p_setupViews];
    
}

#pragma mark -- 把地图加在视图上

- (void)p_addMapView
{
    //显示地图
    self.mapView = [[BMKMapView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64 - 49)];
    //切换为普通视图
    [self.mapView setMapType:(BMKMapTypeStandard)];
    //打开实时路况图层
    [self.mapView setTrafficEnabled:YES];
    //缩放尺度
    self.mapView.zoomLevel = 19;
    //跟随指针模式
    self.mapView.userTrackingMode = BMKUserTrackingModeFollow;
    //比例尺
    self.mapView.showMapScaleBar = YES;
    
    [self.view addSubview:self.mapView];
    
    self.localService = [[BMKLocationService alloc] init];
    self.localService.delegate = self;
    self.localService.userLocation.title = @"当前的位置";
    
    self.localService.userLocation.subtitle = @"正在定位";
    self.mapView.userTrackingMode = BMKUserTrackingModeFollow;
    self.mapView.zoomLevel = 18;
    //精确度
    self.localService.desiredAccuracy = kCLLocationAccuracyBest;
    //启动LocationService
    [self.localService startUserLocationService];
    
    //地理编码
    self.geocodesearch = [[BMKGeoCodeSearch alloc] init];
    [self.mapView setZoomLevel:18];
}
#pragma mark -- 布局

-(void)p_setupViews
{
    //定位的button
    self.bt_locaition = [UIButton buttonWithType:(UIButtonTypeSystem)];
    self.bt_locaition.frame = CGRectMake(5, 10, 32, 32);
    [self.bt_locaition setTitleColor:[UIColor purpleColor] forState:(UIControlStateNormal)];
    [self.mapView addSubview:self.bt_locaition];
    
    //添加点击事件
    [self.bt_locaition addTarget:self action:@selector(bt_locaitionAction:) forControlEvents:(UIControlEventTouchUpInside)];
    //做检索
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemSearch) target:self action:@selector(leftBarButtonItemAction:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor purpleColor];
    
    //搜索框
    self.textField = [[UITextField alloc] init];
    self.textField.frame = CGRectMake(15, 3, self.view.frame.size.width - 30 - 40, 35);
    self.textField.backgroundColor = [UIColor grayColor];
    self.textField.delegate = self;
    self.textField.alpha = 0.6;
    self.textField.layer.cornerRadius = 5;
    self.textField.returnKeyType = UIReturnKeySearch;
    self.textField.placeholder = @"请输入你要搜索的周边位置信息";
    self.textField.clearButtonMode = UITextFieldViewModeAlways;
    self.textField.clearsOnBeginEditing = YES;
    self.textField.leftViewMode = UITextFieldViewModeAlways;
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 15, 35)];
    self.textField.leftView = view;
    self.textField.hidden = YES;
    [self.mapView addSubview:self.textField];
    
    //取消btn
    self.bt_cancel = [UIButton buttonWithType:(UIButtonTypeSystem)];
    self.bt_cancel.frame = CGRectMake(CGRectGetMaxX(self.textField.frame) + 9, 3, 32, 32);
    [self.bt_cancel setTitle:@"取消" forState:(UIControlStateNormal)];
    self.bt_cancel.tintColor = [UIColor grayColor];
    [self.mapView addSubview:self.bt_cancel];
    self.bt_cancel.hidden = YES;
    [self.bt_cancel addTarget:self action:@selector(bt_cancelAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
}

#pragma mark -- 所有的点击的事件
//定位
-(void)bt_locaitionAction:(UIButton *)sender
{
    self.localService = [[BMKLocationService alloc]init];
    self.localService.delegate = self;
    self.localService.userLocation.title = @"当前的位置";
    self.localService.userLocation.subtitle = @"正在定位";
    self.mapView.userTrackingMode = BMKUserTrackingModeFollow;
    self.mapView.zoomLevel = 18;
    self.localService.desiredAccuracy = kCLLocationAccuracyBest;
    //启动LocationService
    [self.localService startUserLocationService];
}
//搜索
-(void)leftBarButtonItemAction:(UIBarButtonItem *)sender
{
    self.textField.hidden = NO;
    self.bt_cancel.hidden = NO;
}
//取消
-(void)bt_cancelAction:(UIButton *)sender
{
    self.textField.hidden = YES;
    self.bt_cancel.hidden = YES;
    [self.textField resignFirstResponder];
}

#pragma mark -- UITextFiledDelegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if ([self.textField.text length] == 0) {
        
        //弹出提示框
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"周边搜索内容不能为空" preferredStyle:(UIAlertControllerStyleAlert)];
        [self presentViewController:alert animated:YES completion:^{
            
        }];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:action];
        return NO;
    }else
    {
        
        //开始检索
        self.curPage = 0;
        self.searcher = [[BMKPoiSearch alloc] init];
        self.searcher.delegate = self;
        BMKNearbySearchOption *option = [[BMKNearbySearchOption alloc] init];
        option.pageIndex = self.curPage;
        //搜索个数
        option.pageCapacity = 17;
        option.location = CLLocationCoordinate2DMake(self.current_latitude, self.current_location);
        option.keyword = self.textField.text;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            BOOL flag2 = [_searcher poiSearchNearBy:option];
            if (flag2) {
                
            }else
            {
                NSLog(@"周边检索失败");
            }

        });
                return YES;
    }
    
}


#pragma mark -- BMKPoiSearchDeleage
-(void)onGetPoiResult:(BMKPoiSearch *)searcher result:(BMKPoiResult *)poiResult errorCode:(BMKSearchErrorCode)errorCode
{
    [self.textField resignFirstResponder];
    //清除屏幕中的所有的annotation
    NSArray *array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    
    if (errorCode == BMK_SEARCH_NO_ERROR) {
        NSMutableArray *annotations = [NSMutableArray array];
        for (int i = 0; i < poiResult.poiInfoList.count; i++) {
            BMKPoiInfo *poi = [poiResult.poiInfoList objectAtIndex:i];
            BMKPointAnnotation *item = [[BMKPointAnnotation alloc] init];
            item.coordinate = poi.pt;
            item.title = poi.name;
            [annotations addObject:item];
        }
        [_mapView addAnnotations:annotations];
        [_mapView showAnnotations:array animated:YES];
    }else if (errorCode == BMK_SEARCH_AMBIGUOUS_ROURE_ADDR){
        NSLog(@"起始点有歧义");
    }else{
        //各种情况的判断
    }
    
    
}




#pragma mark -- BMKGeoCodeSearchDelegate代理 ，这个是地理反编码
-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    if (error == 0) {
        self.localService.userLocation.title = @"当前位置";
        //获取位置
        self.localService.userLocation.subtitle = result.address;
    }
    
}

#pragma mark -- BMKLocationServiceDelegate代理，也为定位服务
//处理位置坐标的更新
-(void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    //一下_mapView为BMKMapView对象
    self.mapView.showsUserLocation = YES;//显示定位图层
    [self.mapView updateLocationData:userLocation];
    
    //开始定位的时候，得到定位编码
    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){0,0};
    if (userLocation.location.coordinate.longitude != 0 && userLocation.location.coordinate.latitude != 0) {
        pt = (CLLocationCoordinate2D){userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude};
    }
    BMKReverseGeoCodeOption *reverseGeoCodeOption = [[BMKReverseGeoCodeOption alloc] init];
    reverseGeoCodeOption.reverseGeoPoint = pt;
    BOOL flag1 = [_geocodesearch reverseGeoCode:reverseGeoCodeOption];
    if (flag1) {
        
    }else{
        NSLog(@"反检索成功");
    }
    self.current_location = userLocation.location.coordinate.longitude;
    self.current_latitude = userLocation.location.coordinate.latitude;
}



#pragma mark -- 当视图出现的时候，和消失的时候
-(void)viewWillAppear:(BOOL)animated
{
    [_mapView viewWillAppear];
    _mapView.delegate = self; // 此处记得不用的时候需要置nil,否则影响内存释放
    _poiSearch.delegate = self;
    _geoCodeSearch.delegate = self;
}

-(void)viewDidAppear:(BOOL)animated
{
    [_mapView viewWillDisappear];//不用时置为nil
    _mapView.delegate = nil;
    _poiSearch.delegate = nil;
    _geoCodeSearch.delegate =nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

